import Overlay from "ol/Overlay";
import { getArea, getLength } from "ol/sphere";
export default class Feature {
	constructor() {}

	showTip(evt, type, baseMap) {
		// 绘制的图形的几何信息
		let sketch = evt.feature;
		let geom = sketch.getGeometry();
		let result;

		let measureTooltipElement = null;
		let measureTooltip = null;
		let tooltipCoord;

		switch (type) {
			case "Point":
				break;
			case "LineString":
				result = this.formatLength(geom);
				tooltipCoord = geom.getLastCoordinate();
				break;
			case "Polygon":
				result = this.formatArea(geom);
				tooltipCoord = geom.getLastCoordinate();
				break;
			case "Circle":
				result = this.formatCircleArea(geom, baseMap);
				tooltipCoord = geom.getLastCoordinate();
				break;
			case "Rectangle":
				result = this.formatArea(geom);
				tooltipCoord = geom.getLastCoordinate();
				break;
		}
		let tip = this.createMeasureTooltip(
			measureTooltipElement,
			measureTooltip,
			result
		);
		tip.setPosition(tooltipCoord);
		return tip;
	}

	formatLength(line) {
		// 距离
		const length = getLength(line, { projection: "EPSG:4326" });
		let output;
		if (length > 100) {
			output = Math.round((length / 1000) * 100) / 100 + " " + "km";
		} else {
			output = Math.round(length * 100) / 100 + " " + "m";
		}
		return output;
	}

	formatArea(polygon) {
		// 面积
		const area = getArea(polygon, { projection: "EPSG:4326" });
		console.log("area;", area);
		let output;
		if (area > 10000) {
			output = Math.round((area / 1000000) * 100) / 100 + " " + "km²";
		} else {
			output = Math.round(area * 100) / 100 + " " + "m²";
		}
		return output;
	}

	formatCircleArea(circle, baseMap) {
		//半径
		let metersPerUnit = baseMap.getView().getProjection().getMetersPerUnit();
		console.log("metersPerUnit;", metersPerUnit);
		const radius = circle.getRadius() * metersPerUnit;
		const area = Math.PI * radius * radius;
		console.log("area", area);
		let output;
		if (area > 10000) {
			output = Math.round((area / 1000000) * 100) / 100 + " " + "km²";
		} else {
			output = Math.round(area * 100) / 100 + " " + "m²";
		}
		return output;
	}

	// tip样式
	createMeasureTooltip(i, tip, result) {
		if (i) {
			i.parentNode.removeChild(i);
		}
		let style =
			"position: relative; background: rgba(100, 176, 215, 1);" +
			"border-radius: 4px; color: white; padding: 4px 8px;" +
			"opacity: 1; white-space: nowrap; font-size: 12px;" +
			"cursor: default; user-select: none;";
		i = document.createElement("div");
		// css
		i.style.cssText = style;
		i.innerHTML = result;
		tip = new Overlay({
			element: i,
			offset: [0, -15],
			positioning: "bottom-center",
			stopEvent: false,
			insertFirst: false,
		});
		return tip;
	}
}
